//
// Created by Wirano on 2020/11/11.
//

#include "Drv_spi.h"
#include "main.h"

extern SPI_HandleTypeDef hspi2;

void Drv_SPI2_init(void)
{
/* USER CODE BEGIN SPI2_Init 0 */

    /* USER CODE END SPI2_Init 0 */

    /* USER CODE BEGIN SPI2_Init 1 */

    /* USER CODE END SPI2_Init 1 */
    /* SPI2 parameter configuration*/
    hspi2.Instance = SPI2;
    hspi2.Init.Mode = SPI_MODE_MASTER;
    hspi2.Init.Direction = SPI_DIRECTION_2LINES;
    hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
    hspi2.Init.CLKPolarity = SPI_POLARITY_LOW;
    hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
    hspi2.Init.NSS = SPI_NSS_SOFT;
    hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
    hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
    hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
    hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
    hspi2.Init.CRCPolynomial = 7;
    if (HAL_SPI_Init(&hspi2) != HAL_OK)
    {
        Error_Handler();
    }
    /* USER CODE BEGIN SPI2_Init 2 */
    __HAL_SPI_ENABLE(&hspi2);
    /* USER CODE END SPI2_Init 2 */

}

uint8_t Drv_SPI2_RW(uint8_t dat)
{
//    while (__HAL_SPI_GET_FLAG(&hspi2, SPI_FLAG_TXE));
//    SPI_I2S_SendData(SPI2, dat);
//    while (__HAL_SPI_GET_FLAG(&hspi2, SPI_FLAG_RXNE));
//    return SPI_I2S_ReceiveData(SPI2);

//    uint8_t rec;
//    HAL_SPI_TransmitReceive(&hspi2, &dat, &rec, sizeof(rec), 1);
//    return rec;

    while(__HAL_SPI_GET_FLAG(&hspi2,SPI_FLAG_TXE) == RESET);//等待发送空闲标志位
    SPI2->DR = dat;//装填预发送数据
    while(__HAL_SPI_GET_FLAG(&hspi2,SPI_FLAG_RXNE) == RESET);//等待接收空闲标志位
    return SPI2->DR;
}

void Drv_SPI2_Transmit(uint8_t *pData, uint16_t Size)
{
    for (uint16_t i = 0; i < Size; i++)
    {
        Drv_SPI2_RW(pData[i]);
    }
}

void Drv_SPI2_Receive(uint8_t *pData, uint16_t Size)
{
    for (uint16_t i = 0; i < Size; i++)
    {
        pData[i] = Drv_SPI2_RW(0);
    }
}

